package com.zzptc.zzsgz.bdsjws.services;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import com.socks.library.KLog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zzptc.zzsgz.bdsjws.MyApplication;
import com.zzptc.zzsgz.bdsjws.R;
import com.zzptc.zzsgz.bdsjws.activities.UpdateActivity;
import com.zzptc.zzsgz.bdsjws.utils.MyUtil;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by zzsgz on 2017/5/21.
 */

public class MyDownLoadService extends Service {
    NotificationCompat.Builder notification;
    NotificationManager notificationManager;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 1)	通过intent接收APK所在的地址
        String url=null;
        if(intent!=null) {
            url = intent.getStringExtra("apkurl");
        }
        // Toast.makeText(this, url+"", Toast.LENGTH_SHORT).show();
        //2、创建通知栏
        createNotification();
        //3、下载
        //首先判断判断是否存在SD卡   得到文件存储路径
        File file= MyUtil.getDir();
        //下载
        downloadfile(url,file);//两个参数分别表示：1、从哪取  2、放哪儿
        return super.onStartCommand(intent, flags, startId);
//        1)	通过intent接收APK所在的地址
//        2)	创建通知栏(下载之前，要判断是否存在SD卡，有就存储在SD卡，没有存储在系统的内部存储中)
//        3)	下载apk

    }
    //下载
    private void downloadfile(String url,final File file) {
        //使用OKHttp进行文件下载
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new FileCallBack(file.getAbsolutePath(),"hhhhh.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        notification.setContentText("下载失败");
                        notificationManager.notify(0,notification.build());
                    }
                    //下载完毕
                    @Override
                    public void onResponse(File response, int id) {
                        notification.setContentText("下载完毕");
                        notification.setAutoCancel(true);
                        notificationManager.notify(0,notification.build());
                        //安装   点击后安装
                        // installApk(file);
                        //第一步：得到一个用于安装的Intent
                        Intent intent=MyUtil.getInstallIntent(response);
                        startActivity(intent);
//                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(MyDownLoadService.this);
//                        stackBuilder.addParentStack(UpdateActivity.class);
//                        stackBuilder.addNextIntent(intent);
//                        PendingIntent resultPendingIntent =
//                                stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
//                        notification.setContentIntent(resultPendingIntent);
//                        //让进度条消失
//                        notification.setProgress(0,0,false);
//                        notification.setContentText("请点击安装");
//                        notification.setContentTitle("下载完毕");
                        notificationManager.notify(0,notification.build());

                    }
                    //正在下载
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        KLog.i("======================",progress);
                        // System.out.println("progress++++++++++++++++++++++++++++"+progress);
                        //Log.i("====================",progress+"");
                        notification.setProgress(100, (int) (progress*100),false);
                        notification.setContentText("已经下载了"+(int)(progress*100)+"%");
                        notificationManager.notify(0,notification.build());
                    }
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                    }
                });
    }
    //创建通知栏
    public void createNotification(){
        notificationManager= (NotificationManager) MyApplication.getContext().getSystemService(NOTIFICATION_SERVICE);
        notification=new NotificationCompat.Builder(MyApplication.getContext());
        notification.setSmallIcon(R.mipmap.logo_small)
                .setContentText("正在下载")
                .setContentTitle("百度卫士下载")
                .setAutoCancel(false)//设置用户不能取消
                .build();
        notificationManager.notify(0,notification.build());
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
